package com.wbao.dianniu.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.utility.IMAutoLoginInfoStoreUtil;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.LoadingDialog;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.im.NotificationInitSampleHelper;
import com.wbao.dianniu.im.UserProfileSampleHelper;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.manager.LoginManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

/**
 * Created by yejianjun on 2018/1/16.
 */

public class BaseLoginActivity extends Activity implements ILoginListener {

    private YWIMKit mIMKit;
    private boolean isShowDialog = false;
    private Dialog pDialog;
    private LoginManager manager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initManager();
    }

    private void initManager() {
        manager = new LoginManager(this);
        manager.addLoginListener(this);
    }


    public void setIsShowDialog(boolean isShow) {
        isShowDialog = isShow;
    }

    private void login(String username, String password) {
        // 判断用户名
        if (null == username) {
            Notification.toast(BaseLoginActivity.this, getResources().getString(R.string.login_error_2));
        } else if (null == password) {
            Notification.toast(BaseLoginActivity.this, getResources().getString(R.string.login_error_3));
        } else {
            /** 是否为手机号码 */
            boolean ismobile = username.matches("^(13|15|18|14|17)\\d{9}$");
            if (!ismobile) {
                Notification.toast(BaseLoginActivity.this, getResources().getString(R.string.login_error_1));
                return;
            }
            if (isShowDialog) {
                showWaittingDialog();
            }
            String longitude = SharedPreferencesUtils.getLongitude(this);
            String latitude = SharedPreferencesUtils.getLatitude(this);
            // 发送登录请求
            manager.Login(this, username, Utils.Md5(password), Utils.getDeviceId(this), longitude, latitude, Utils.getVersionName(BaseLoginActivity.this), null);
        }

    }


    @Override
    public void onLoginFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onLoginSuccess(LoginResponse objdata) {
        Utils.saveLoginData(this, objdata);
        init(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), getResources().getString(R.string.app_key));
        //登录成功时，登录IM
        loginIM(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), objdata.getAccountInfo().getPwd());

    }

    private void init(String userId, String appKey) {
        final String hisUserId = IMAutoLoginInfoStoreUtil.getLoginUserId();
        if (!hisUserId.equals(userId) && !hisUserId.isEmpty()) {    // 两次登录用户不同 先调用登出命令再调用登录命令
            LoginSampleHelper.getInstance().loginOut_Sample();
        }
        //初始化imkit
        LoginSampleHelper.getInstance().initIMKit(userId, appKey);
        //自定义头像和昵称回调初始化(如果不需要自定义头像和昵称，则可以省去)
        UserProfileSampleHelper.initProfileCallback();
        //通知栏相关的初始化
        NotificationInitSampleHelper.init();
    }

    public void loginIM(final String userId, final String password) {
        if (null == LoginSampleHelper.getInstance().getIMKit()) {
            //初始化imik
            LoginSampleHelper.getInstance().initIMKit(userId, getResources().getString(R.string.app_key));
        }
        mIMKit = LoginSampleHelper.getInstance().getIMKit();
        //开始登录
        if (null == mIMKit) {
            return;
        }
//        Log.d(TAG, "开始登录IM：" + System.currentTimeMillis() + "");
        IYWLoginService loginService = mIMKit.getLoginService();
        YWLoginParam loginParam = YWLoginParam.createLoginParam(userId, password);
        loginService.login(loginParam, new IWxCallback() {

            @Override
            public void onSuccess(Object... arg0) {
                if (isShowDialog) {
                    if (null != pDialog && pDialog.isShowing()) {
                        pDialog.dismiss();
                    }
                }
                // 保存自动登录配置信息
                saveConfigInfo(userId, password);
                // 成功 界面跳转
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.setClass(BaseLoginActivity.this, MainActivity.class);
                startActivity(intent);
                BaseLoginActivity.this.finish();
            }

            @Override
            public void onProgress(int arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onError(int errCode, String description) {
                if (isShowDialog) {
                    if (null != pDialog && pDialog.isShowing()) {
                        pDialog.dismiss();
                    }
                }
                //如果登录失败，errCode为错误码,description是错误的具体描述信息
                if (null != description) {
                    Notification.toast(BaseLoginActivity.this, description);
                } else {
                    Notification.toast(BaseLoginActivity.this, "【登录失败，错误码】：" + errCode);
                }

            }
        });
    }

    /**
     * 保存用户登录用户名及MD5加密过的密码
     *
     * @param userName
     * @param pwd
     */
    private void saveConfigInfo(String userName, String pwd) {
        SharedPreferencesUtils.init(BaseLoginActivity.this);
        SharedPreferencesUtils.setUserName(userName);
        SharedPreferencesUtils.setPassword(pwd);
        SharedPreferencesUtils.setAutoLoginStatus(true);
    }

    private void showWaittingDialog() {
        pDialog = LoadingDialog.createLoadingDialog(this, "正在登录...");
        pDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeLoginListener(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("");
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("");
    }
}
